﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace DAL
{
    /// <summary>
    /// Summary description for Product
    /// </summary>
    public partial class Product
    {
        public static string GetShortDescription(string description)
        {
            int dLimit = 220;
            if (description.Length > dLimit)
            {
                description = string.Format("{0}...", description.Substring(0, dLimit));
            }
            return description;
        }

        public static void MakeDefaultImage(int imageId, int productId)
        {
            if (System.Web.Security.Roles.IsUserInRole("Administrator"))
            {
                using (DAL.EShopDBDataContext db = new DAL.EShopDBDataContext())
                {
                    var p = db.Products.Single(c => c.ProductId == productId);
                    p.DefaultImageId = imageId;
                    db.SubmitChanges();
                }
            }
        }

        public List<DAL.Product> SearchProducts(string title, int categoryId)
        {
            EShopDBDataContext db = new EShopDBDataContext();
            if (categoryId > 0)
            {
                var p = from c in db.Products
                        where c.Title.ToUpper().Contains(title.ToUpper()) && c.CategoryId == categoryId
                        orderby c.DefaultImageId descending
                        select c;
                return p.ToList();
            }
            else
            {
                var p = from c in db.Products
                        where c.Title.ToUpper().Contains(title.ToUpper())
                        orderby c.DefaultImageId descending
                        select c;
                return p.ToList();
            }
        }
        public static void DeleteImage(int imageId, int productId, string appPath)
        {
            if (System.Web.Security.Roles.IsUserInRole("Administrator"))
            {
                using (DAL.EShopDBDataContext db = new DAL.EShopDBDataContext())
                {
                    var p = db.Products.Single(c => c.ProductId == productId);
                    if (p.ProductImages.Count == 1)
                        p.DefaultImageId = 1;
                    var pi = db.ProductImages.Single(c => c.ImageId == imageId);
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
                    {
                        string fileName = string.Format("{0}{1}", appPath, pi.Url);
                        db.ProductImages.DeleteOnSubmit(pi);
                        db.SubmitChanges();
                        if (System.IO.File.Exists(fileName) && !string.IsNullOrEmpty(pi.Url))
                            System.IO.File.Delete(fileName);
                        ts.Complete();

                    }
                }
            }
        }

        public List<DAL.Product> GetBestsellingProducts(int count)
        {
            using (EShopDBDataContext db = new EShopDBDataContext())
            {
                return db.Product_GetBestSellingProducts(count).ToList<Product>();
            }
        }

        public void SetBrand(string brandName)
        {
            using (DAL.EShopDBDataContext db = new DAL.EShopDBDataContext())
            {
                int count = (from c in db.Brands
                             where c.Title == brandName
                             select c).Count();
                if (count > 0)
                {
                    this.BrandId = (from c in db.Brands
                                    where c.Title == brandName
                                    select c.BrandId).Single();
                }
                else
                {
                    var brandId = db.Brands.Max(c => c.BrandId) + 1;
                    Brand brand = new Brand { Title = brandName, BrandId = brandId };
                    db.Brands.InsertOnSubmit(brand);
                    db.SubmitChanges();
                    this.BrandId = brand.BrandId;
                }
            }
        }

        public void SetWarranty(string warrantyValue)
        {
            if (string.IsNullOrEmpty(warrantyValue))
                return;
            using (DAL.EShopDBDataContext db = new DAL.EShopDBDataContext())
            {
                int count = (from c in db.Warranties
                             where c.Value == warrantyValue
                             select c).Count();
                if (count > 0)
                {
                    this.WarrantyId = (from c in db.Warranties
                                       where c.Value == warrantyValue
                                       select c.WarrantyId).Single();
                }
                else
                {
                    Warranty warranty = new Warranty { Value = warrantyValue };
                    db.Warranties.InsertOnSubmit(warranty);
                    db.SubmitChanges();
                    this.WarrantyId = warranty.WarrantyId;
                }
            }
        }

        public static string GetForwardLink(int index, int catId, int brandId)
        {
            if (index != 0)
            {
                using (DAL.EShopDBDataContext db = new DAL.EShopDBDataContext(ConfigurationManager.ConnectionStrings["EShopConnectionString"].ConnectionString))
                {
                    if (brandId != 0 && catId == 0)
                    {
                        var products = db.Brand_GetProduct(brandId, index + 1);
                        foreach (DAL.Product p in products)
                            return string.Format("?index={0}&id={1}&brandId={2}", index + 1, p.ProductId, brandId);
                        return "#";
                    }
                    if (catId != 0 && brandId != 0)
                    {
                        var products = db.Category_GetBrandProduct(catId, brandId, index + 1);
                        foreach (DAL.Product p in products)
                            return string.Format("?catId={0}&index={1}&id={2}&brandId={3}", catId, index + 1, p.ProductId, brandId);
                        return "#";
                    }
                    if (catId != 0 && brandId == 0)
                    {
                        var products = db.Category_GetProduct(catId, index + 1);
                        foreach (DAL.Product p in products)
                            return string.Format("?catId={0}&index={1}&id={2}", catId, index + 1, p.ProductId);
                        return "#";
                    }
                }
            }
            return "#";
        }

        public static string GetBackLink(int index, int catId, int brandId)
        {
            if (index != 0 && index != 1)
            {
                using (DAL.EShopDBDataContext db = new DAL.EShopDBDataContext(ConfigurationManager.ConnectionStrings["EShopConnectionString"].ConnectionString))
                {
                    if (brandId != 0 && catId == 0)
                    {
                        var products = db.Brand_GetProduct(brandId, index - 1);
                        foreach (DAL.Product p in products)
                            return string.Format("?index={0}&id={1}&brandId={2}", index - 1, p.ProductId, brandId);
                        return "#";
                    }
                    if (catId != 0 && brandId != 0)
                    {
                        var products = db.Category_GetBrandProduct(catId, brandId, index - 1);
                        foreach (DAL.Product p in products)
                            return string.Format("?catId={0}&index={1}&id={2}&brandId={3}", catId, index - 1, p.ProductId, brandId);
                        return "#";
                    }
                    if (catId != 0 && brandId == 0)
                    {
                        var p = db.Category_GetProduct(catId, index - 1).Single();
                        return string.Format("?catId={0}&index={1}&id={2}", catId, index - 1, p.ProductId);
                    }
                }
            }
            return "#";
        }
        //TODO Implement Set prices
        public static void SetPrices(string sourcePrice, string operatorValue, int percentValue)
        {
            using (DAL.EShopDBDataContext db = new EShopDBDataContext())
            {
                foreach (Product p in db.Products)
                    p.Price = p.DealerPrice;
                db.SubmitChanges();
            }
        }

        public static Product GetProductByID(int productId)
        {
            using (DAL.EShopDBDataContext db = new EShopDBDataContext())
                return db.Products.Single(c => c.ProductId == productId);
        }

        #region IDisposable Members

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        #endregion

    }
}
